<template>
  <div class="order-management-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">
        <i class="el-icon-s-order"></i>
        订单管理
      </h2>
      <p class="page-description">管理您的订单信息，查看订单状态和详情</p>
    </div>

    <!-- 订单列表 -->
    <div class="order-list">
      <el-card>
        <div slot="header" class="card-header">
          <span>订单列表</span>
          <div class="header-actions">
            <el-button
              type="primary"
              icon="el-icon-refresh"
              size="small"
              @click="loadOrderData">
              刷新
            </el-button>
            <el-button
              type="success"
              icon="el-icon-download"
              size="small"
              @click="handleExport">
              导出
            </el-button>
          </div>
        </div>

        <!-- 搜索筛选 -->
        <div class="search-section">
          <el-form :model="searchForm" :inline="true" class="search-form">
            <el-form-item label="下单时间">
              <el-date-picker
                v-model="searchForm.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                style="width: 240px">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="订单状态">
              <el-select v-model="searchForm.statue" placeholder="请选择状态" clearable style="width: 120px">
                <el-option label="待支付" :value="0"></el-option>
                <el-option label="已支付" :value="1"></el-option>
                <el-option label="已取消" :value="-1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="handleSearch">查询</el-button>
              <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 订单表格 -->
        <configurable-table
          :columns="tableColumns"
          :data="orderList"
          :loading="loading"
          :show-pagination="true"
          :current-page.sync="pagination.current"
          :page-size.sync="pagination.size"
          :pagination-total="pagination.total"
          @page-change="loadOrderData"
          stripe>
          <!-- 订单状态列 -->
          <template #status="{ row }">
            <el-tag :type="getStatusType(row.statue)">
              {{ getStatusText(row.statue) }}
            </el-tag>
          </template>

          <!-- 操作列 -->
          <template #actions="{ row }">
            <el-button
              type="text"
              size="small"
              @click="handleViewDetail(row)">
              查看详情
            </el-button>
          </template>
        </configurable-table>
      </el-card>
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog
      title="订单详情"
      :visible.sync="detailDialogVisible"
      width="900px"
      custom-class="view-dialog"
      :close-on-click-modal="false">
      <div class="detail-content" v-if="selectedOrder">
        <!-- 订单状态横幅 -->
        <div class="status-banner" :class="getStatusBannerClass(selectedOrder.statue)">
          <div class="status-icon">
            <i :class="getStatusIcon(selectedOrder.statue)"></i>
          </div>
          <div class="status-info">
            <div class="status-label">订单状态</div>
            <div class="status-value">{{ getStatusText(selectedOrder.statue) }}</div>
          </div>
        </div>

        <!-- 订单基本信息 -->
        <div class="info-section">
          <div class="section-title">
            <i class="el-icon-tickets"></i>
            <span>订单基本信息</span>
          </div>
          <el-row :gutter="20" class="info-row">
            <el-col :span="12">
              <div class="info-item">
                <div class="info-label">
                  <i class="el-icon-files"></i>
                  订单ID
                </div>
                <div class="info-value">{{ selectedOrder.id || '-' }}</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <div class="info-label">
                  <i class="el-icon-time"></i>
                  下单时间
                </div>
                <div class="info-value">{{ formatDateTime(selectedOrder.createTime) }}</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <div class="info-label">
                  <i class="el-icon-refresh"></i>
                  更新时间
                </div>
                <div class="info-value">{{ formatDateTime(selectedOrder.updateTime) }}</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <div class="info-label">
                  <i class="el-icon-user"></i>
                  用户ID
                </div>
                <div class="info-value">{{ selectedOrder.cuserId || '-' }}</div>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 商品信息 -->
        <div class="info-section">
          <div class="section-title">
            <i class="el-icon-goods"></i>
            <span>商品信息</span>
          </div>
          <el-row :gutter="20" class="info-row">
            <el-col :span="12">
              <div class="info-item">
                <div class="info-label">
                  <i class="el-icon-box"></i>
                  商品ID
                </div>
                <div class="info-value">{{ selectedOrder.productId || '-' }}</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <div class="info-label">
                  <i class="el-icon-shopping-cart-full"></i>
                  商品数量
                </div>
                <div class="info-value">
                  <el-tag type="info" size="small">{{ selectedOrder.num || 0 }} 件</el-tag>
                </div>
              </div>
            </el-col>
            <el-col :span="24">
              <div class="info-item">
                <div class="info-label">
                  <i class="el-icon-goods"></i>
                  商品名称
                </div>
                <div class="info-value">{{ selectedOrder.productName || '-' }}</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <div class="info-label">
                  <i class="el-icon-price-tag"></i>
                  商品单价
                </div>
                <div class="info-value amount-text">¥{{ formatPrice(selectedOrder.productPrice) }}</div>
              </div>
            </el-col>
            <el-col :span="12" v-if="selectedOrder.attribute">
              <div class="info-item">
                <div class="info-label">
                  <i class="el-icon-s-operation"></i>
                  商品属性
                </div>
                <div class="info-value">{{ selectedOrder.attribute || '-' }}</div>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 金额信息 -->
        <div class="info-section highlight-section">
          <div class="section-title">
            <i class="el-icon-wallet"></i>
            <span>金额信息</span>
          </div>
          <el-row :gutter="20" class="info-row">
            <el-col :span="12">
              <div class="info-item highlight-item">
                <div class="info-label">
                  <i class="el-icon-money"></i>
                  订单金额
                </div>
                <div class="info-value amount-text">
                  ¥{{ formatPrice(selectedOrder.amount) }}
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item highlight-item">
                <div class="info-label">
                  <i class="el-icon-coin"></i>
                  积分金额
                </div>
                <div class="info-value point-text">
                  ¥{{ formatPrice(selectedOrder.pointAmount) }}
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item highlight-item">
                <div class="info-label">
                  <i class="el-icon-wallet"></i>
                  支付金额
                </div>
                <div class="info-value pay-text">
                  ¥{{ formatPrice(selectedOrder.payAmount) }}
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getMerchantOrderPage, getMerchantOrderList, getMerchantOrderDetail } from '@/api/merchant/order-management'

export default {
  name: 'MerchantOrderManagement',
  data() {
    return {
      loading: false,

      // 搜索表单
      searchForm: {
        dateRange: [],
        statue: null
      },

      // 订单列表
      orderList: [],

      // 分页
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },

      // 表格列配置
      tableColumns: [
        { prop: 'id', label: '订单ID', minWidth: 100 },
        { prop: 'productName', label: '商品名称', minWidth: 150, showOverflowTooltip: true },
        {
          prop: 'amount',
          label: '订单金额',
          minWidth: 120,
          formatter: (row, column, cellValue) => {
            return this.formatPrice(cellValue)
          }
        },
        {
          prop: 'pointAmount',
          label: '积分金额',
          minWidth: 120,
          formatter: (row, column, cellValue) => {
            return this.formatPrice(cellValue)
          }
        },
        {
          prop: 'payAmount',
          label: '支付金额',
          minWidth: 120,
          formatter: (row, column, cellValue) => {
            return this.formatPrice(cellValue)
          }
        },
        { prop: 'statue', label: '订单状态', minWidth: 100, slot: 'status' },
        {
          prop: 'createTime',
          label: '下单时间',
          minWidth: 150,
          formatter: (row, column, cellValue) => {
            return this.formatDateTime(cellValue)
          }
        },
        {
          prop: 'updateTime',
          label: '更新时间',
          minWidth: 150,
          formatter: (row, column, cellValue) => {
            return this.formatDateTime(cellValue)
          }
        },
        { label: '操作', minWidth: 100, slot: 'actions' }
      ],

      // 详情对话框
      detailDialogVisible: false,
      selectedOrder: null
    }
  },
  mounted() {
    this.loadOrderData()
  },
  methods: {
    // 加载订单数据
    async loadOrderData() {
      this.loading = true
      try {
        Logger.log('=== 加载商家订单数据 ===')

        const params = {
          pageIndex: this.pagination.current,
          pageSize: this.pagination.size,
          merchantId: this.$store.state.user.id // 商家ID
        }

        // 添加时间筛选
        if (this.searchForm.dateRange && this.searchForm.dateRange.length === 2) {
          params.startTime = this.searchForm.dateRange[0] + ' 00:00:00'
          params.endTime = this.searchForm.dateRange[1] + ' 23:59:59'
        }

        // 添加状态筛选
        if (this.searchForm.statue !== null && this.searchForm.statue !== '') {
          params.statue = this.searchForm.statue
        }

        Logger.log('订单查询参数:', params)

        const response = await getMerchantOrderPage(params)
        Logger.log('订单响应:', response.data)

        if (response.code === 0 && response.data) {
          this.orderList = response.data.list || []
          this.pagination.total = response.data.total || 0
          Logger.log('订单数据:', this.orderList)
        } else {
          Logger.log('未获取到订单数据')
          this.orderList = []
          this.pagination.total = 0
        }
      } catch (error) {
        Logger.error('加载订单数据失败:', error)
        this.$message.error('加载订单数据失败，请重试')
        this.orderList = []
        this.pagination.total = 0
      } finally {
        this.loading = false
      }
    },

    // 查看订单详情
    async handleViewDetail(row) {
      try {
        Logger.log('=== 查看订单详情 ===')
        Logger.log('订单ID:', row.id)

        const response = await getMerchantOrderDetail(row.id)
        Logger.log('订单详情响应:', response.data)

        if (response.code === 0 && response.data) {
          this.selectedOrder = response.data
          this.detailDialogVisible = true
        } else {
          this.$message.error('获取订单详情失败')
        }
      } catch (error) {
        Logger.error('获取订单详情失败:', error)
        this.$message.error('获取订单详情失败，请重试')
      }
    },

    // 导出订单
    async handleExport() {
      try {
        Logger.log('=== 导出订单数据 ===')

        const params = {
          merchantId: this.$store.state.user.id
        }

        // 添加时间筛选
        if (this.searchForm.dateRange && this.searchForm.dateRange.length === 2) {
          params.startTime = this.searchForm.dateRange[0] + ' 00:00:00'
          params.endTime = this.searchForm.dateRange[1] + ' 23:59:59'
        }

        // 添加状态筛选
        if (this.searchForm.statue !== null && this.searchForm.statue !== '') {
          params.statue = this.searchForm.statue
        }

        Logger.log('导出参数:', params)

        const response = await getMerchantOrderList(params)
        Logger.log('导出响应:', response.data)

        if (response.code === 0 && response.data) {
          const orders = response.data.list || []

          if (orders.length === 0) {
            this.$message.warning('没有可导出的订单数据')
            return
          }

          // 使用全局方法：将表格列配置转换为导出列配置
          const exportColumns = this.$convertTableColumnsToExport(
            this.tableColumns,
            {
              // 为使用了 slot 的列提供格式化函数
              statue: (value) => this.getStatusText(value)
            },
            {
              // 排除操作列
              excludeProps: ['actions']
            }
          )

          // 使用全局方法：导出Excel文件
          this.$export(
            'excel',
            orders,
            exportColumns,
            `商家订单数据_${new Date().toISOString().split('T')[0]}`,
            {
              sheetName: '订单数据',
              textColumns: [0] // 将订单ID列设置为文本格式
            }
          )

          this.$message.success(`成功导出 ${orders.length} 条订单数据`)
          Logger.log('成功导出订单数据:', orders.length, '条')
        } else {
          this.$message.error('导出失败')
        }
      } catch (error) {
        Logger.error('导出订单失败:', error)
        this.$message.error('导出订单失败，请重试')
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.current = 1
      this.loadOrderData()
    },

    // 重置搜索
    handleReset() {
      this.searchForm = {
        dateRange: [],
        statue: null
      }
      this.pagination.current = 1
      this.loadOrderData()
    },

    // 获取状态类型
    getStatusType(status) {
      const statusMap = {
        0: 'warning',  // 待支付
        1: 'success',  // 已支付
        '-1': 'info'   // 已取消
      }
      return statusMap[status] || 'info'
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        0: '待支付',
        1: '已支付',
        '-1': '已取消'
      }
      return statusMap[status] || '未知'
    },

    // 获取状态横幅类名
    getStatusBannerClass(status) {
      const statusMap = {
        0: 'status-pending',  // 待支付
        1: 'status-success',  // 已支付
        '-1': 'status-rejected'   // 已取消
      }
      return statusMap[status] || 'status-pending'
    },

    // 获取状态图标类名
    getStatusIcon(status) {
      const statusMap = {
        0: 'el-icon-warning',  // 待支付
        1: 'el-icon-success',  // 已支付
        '-1': 'el-icon-close'   // 已取消
      }
      return statusMap[status] || 'el-icon-warning'
    },

    // 格式化价格
    formatPrice(price) {
      if (!price) return '0.00'
      return (price / 100).toFixed(2)
    },

    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return '-'
      return new Date(dateTime).toLocaleString('zh-CN')
    }
  }
}
</script>

<style scoped>
.order-management-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-description {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.order-list {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.search-section {
  margin-bottom: 16px;
}

.search-form {
  margin-bottom: 0;
}

/* 金额文本样式 */
.amount-text {
  color: #67c23a;
  font-weight: 600;
  font-size: 16px;
}

.point-text {
  color: #e6a23c;
  font-weight: 600;
  font-size: 16px;
}

.pay-text {
  color: #409eff;
  font-weight: 600;
  font-size: 16px;
}

/* 订单详情弹框样式优化 */
.detail-content {
  padding: 0;
}

/* el-col 间距优化 - 给每个 el-col 添加下边距，最后一行去掉 */
.info-row {
  .el-col {
    margin-bottom: 16px;
  }

  /* 去掉最后一个 el-col 的下边距 */
  .el-col:last-child {
    margin-bottom: 0;
  }
}

/* 高亮金额样式 */
.highlight-section .info-item.highlight-item .info-value {
  font-size: 18px;
  font-weight: 700;
}

.highlight-section .info-item.highlight-item .amount-text {
  font-size: 20px;
  color: #67c23a;
}

.highlight-section .info-item.highlight-item .point-text {
  font-size: 20px;
  color: #e6a23c;
}

.highlight-section .info-item.highlight-item .pay-text {
  font-size: 20px;
  color: #409eff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-form {
    display: flex;
    flex-direction: column;
    gap: 16px;
  }

  .search-form .el-form-item {
    margin-right: 0;
  }

  .header-actions {
    flex-direction: column;
    gap: 4px;
  }
}
</style>
